package com.xky.example_student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xky.example_student.entity.Result;
import com.xky.example_student.entity.Student;
import com.xky.example_student.service.StudentService;
import com.xky.example_student.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author adf01
* @description 针对表【student】的数据库操作Service实现
* @createDate 2025-08-05 14:18:33
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
    implements StudentService{
    
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public boolean saveWithStuIdCheck(Student student) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("stu_id",student.getStuId());

        Long count = baseMapper.selectCount(studentQueryWrapper);

        if (count > 0){
            return false;
        }

        return save(student);
    }

    @Override
    public void saveTime(Student student) {
        //手动设置时间
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

    }


    public boolean removeAll(){
        // 1. 查询所有学生的ID
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.select("id");
        List<Student> students = baseMapper.selectList(studentQueryWrapper);

        // 2. 提取ID列表（如果没有数据，直接返回true）
        if (students.isEmpty()){
            return true;
        }

        List<Integer> ids = students.stream()
                .map(Student::getId)
                .toList();

        // 3. 批量删除（使用MyBatis-Plus的removeByIds方法）
        return removeByIds(ids);

    }

    /**
     * 更新方法
     * @param student
     * @return
     */
    @Override
    public boolean updateByIdSa(Student student) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.select("id");
        List<Student> students = baseMapper.selectList(studentQueryWrapper);

        if (students.isEmpty()){
            return false;
        }else {
            return updateById(student);
        }
    }
    
    /**
     * 查询所有学生信息
     * @return 学生列表
     */
    @Override
    public List<Student> listAllStudents() {
        return studentMapper.selectAllStudents();
    }
    
    @Override
    public Page<Student> pageStudents(Page<Student> page) {
        return studentMapper.selectStudentPage(page);
    }
}




